#pragma once

#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include"Sock.hpp"

//底层的Tcp服务端
class TcpServer
{
private:
    int port;
    int listen_sock;
    static TcpServer* svr;
    static pthread_mutex_t lock;
private:
    TcpServer(int _port):port(_port),listen_sock(-1){}
    TcpServer(const TcpServer&)=delete;
    TcpServer& operator=(const TcpServer&)=delete;
public:
    void InitTcpServer()
    {
        listen_sock=Sock::Socket();
        Sock::SetSockOpt(listen_sock);
        Sock::Bind(listen_sock,port);
        Sock::Listen(listen_sock);
    }
    static TcpServer* getInstance(int port)
    {
        if(nullptr==svr)
        {
            pthread_mutex_lock(&lock);
            if(nullptr==svr)
            {
                svr=new TcpServer(port);
                svr->InitTcpServer();
            }
            pthread_mutex_unlock(&lock);
        }
        return svr;
    }
    int Sock()
    {
        return listen_sock;
    }
    ~TcpServer()
    {
        if(listen_sock>=0) close(listen_sock);
    }
};
TcpServer* TcpServer::svr=nullptr;
pthread_mutex_t TcpServer::lock=PTHREAD_MUTEX_INITIALIZER;